package com.dp.ajaxupload.core;

import java.io.IOException;
import java.io.OutputStream;

public class MonitoredOutputStream extends OutputStream
{
    //正真的输出流对象
	private OutputStream target;
	//监听输出流对象的一个监听器
    private OutputStreamListener listener;

    public MonitoredOutputStream(OutputStream target, OutputStreamListener listener)
    {
        this.target = target;
        //启动监听器
        if(listener!=null){
        	 this.listener = listener;
        	 this.listener.start();
        }else{
        	try {
				target.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
       
    }

    public void write(byte b[], int off, int len) throws IOException
    {  
    	//读输出流的内容
        target.write(b,off,len);
        //监听器在记录
        if(listener!=null){
        	 listener.bytesRead(len - off);
        }
       
    }

    public void write(byte b[]) throws IOException
    {
        target.write(b);
        if(listener!=null){
        	listener.bytesRead(b.length);
        }
    }

    public void write(int b) throws IOException
    {
        target.write(b);
        if(listener!=null){
        	listener.bytesRead(1);
        }
        
    }

    public void close() throws IOException
    {   //输出流关闭
        target.close();
        if(listener!=null){
        	 //当前这个文件已经上传完成
        	listener.done();
        }
    }

    public void flush() throws IOException
    {
        target.flush();
        //没有监听器监听
    }
}
